#include "StdAfx.h"
#include "TcpServer.h"

TcpServer::TcpServer()
{
}

TcpServer::~TcpServer()
{
}

void TcpServer::Start(u_short port)
{
    this->port = port; 
    CThread::Start();
}

bool TcpServer::IsStarted()
{
    return CThread::IsStarted();
}

void TcpServer::Stop()
{
    CThread::Stop();
}

void TcpServer::Run()
{
    try
    {
        CSockListener listener;    
        listener.Listen(CSockAddr(INADDR_LOOPBACK, port));

        HANDLE objects[2] = {m_sigStop, listener.GetEvent()};
        for (;;)
        {
            DWORD signal = WaitForMultipleObjects(2, objects, false, INFINITE) - WAIT_OBJECT_0;
            if (signal == 0) break;
          
            CSockTCP* pClient = new CSockTCP();
            pClient->Accept(listener);
               
            SYS::CGuard me(this);
            clients.push_back(pClient);
        }
    }
    catch (CError* pErr)
    {
        TRACE(pErr->GetErrMsg());
        return;
    }
}

void TcpServer::Send(const char* pData, int size)
{
    SYS::CGuard me(this);

    std::vector<std::vector<CSockTCP*>::iterator> dead_clients;
    for (std::vector<CSockTCP*>::iterator it = clients.begin(); it != clients.end(); ++it)
    {
        int err = (*it)->Send(pData, size);
        if (err != 0)
        {
            dead_clients.push_back(it);
        }
    }
    for (std::vector<std::vector<CSockTCP*>::iterator>::reverse_iterator it = dead_clients.rbegin(); it != dead_clients.rend(); ++it)
    {
        delete **it;
        clients.erase(*it);
    }
}

